import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class StreamDemo {
    public static void main(String[] args) {
        PipedInputStream pipedInputStream = new PipedInputStream();
        PipedOutputStream  pipedOutputStream = new PipedOutputStream();

        try {
            pipedInputStream.connect(pipedOutputStream);
            Input in = new Input(pipedInputStream);
            Output out = new Output(pipedOutputStream);
            new Thread(in).start();
            Thread.sleep(1000);
            new Thread(out).start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}

class Input implements Runnable {
    private PipedInputStream pis;
    public Input(PipedInputStream pis) {
        this.pis = pis;
    }

    @Override
    public void run() {
        try {
                while(true) {
                    byte[] buffer = new byte[1024];
                    int read;
                    while ((read = pis.read(buffer)) != -1) {
                        System.out.println("read:" + new String(buffer, 0, read));
                    }
                    //String str = new String(buffer, 0, readBytes.length);
                    //System.out.println("read " + str);
                }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class Output implements Runnable {
    private PipedOutputStream pos;
    int index = 0;
    public Output(PipedOutputStream pos) {
        this.pos = pos;
    }

    @Override
    public void run() {
        String str = "测试sdfasdf ";
        try {
            while(true) {
                index ++;
                pos.write((str + index).getBytes());
                System.out.println("write " + str + index);
                Thread.sleep(500);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}